<?php

require_once(dirname(__FILE__) . '/../classes/Tick.php');

/**
 * Analog fot JavaScript setTimeout
 * @staticvar Tick $tick
 * @param callback $function
 * @param float $time Time in seconds
 */
function setTimeout($function, $time) {
    static $tick = NULL;
    if (NULL === $tick) {
        $tick = Tick::getInstance();
    }

    $endTime = microtime(true) + $time;
    $timeoutId = function(Event $event) use ($endTime, $function) {
                    if (microtime(true) >= $endTime) {
                        try {
                            call_user_func($function);
                        } catch (DieException $e) {
                            echo 'Caught exception: ', $e->getMessage(), "\n";
                        }
                        $event->target->removeEventListener('tick', $event->callee);
                    }
                };
    $tick->addEventListener('tick', $timeoutId);
    return $timeoutId;
}

/**
 * Analog fot JavaScript clearTimeout
 * @staticvar Tick $tick
 * @param callback $timeoutId
 */
function clearTimeout($timeoutId) {
    static $tick = NULL;
    if (NULL === $tick) {
        $tick = Tick::getInstance();
    }
    $tick->removeEventListener('tick', $timeoutId);
}